<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/21 17:39
 * Desc: 用户账户找回
 */
class Service_Api_Member_Find extends Contract_Api_Member_Find
{

    public function user_verify(array $params): array
    {
        /**
         * @var $user
         * @var $msg_code
         * @var $captcha_key
         * @var $code
         */
        extract($params);

        if (!Model_Api_V2_Common::verify_image_code($captcha_key, $code)) {
            throw new Exception(__("checkcode_error"));
        }

        if (!empty($msg_code)) {
            if (Model_Api_V2_Common::cache('get', "reg_findpwd_send_code_{$user}") != $msg_code) {
                throw new Exception(__("account_sms_code_error"));
            }
        }

        //用户不存在
        $member = Model_Member::member_find($user);
        if (empty($member)) {
            throw new Exception(__("error_user_noexists"));
        }

        // 验证成功后清除图片缓存
        Model_Api_V2_Common::cache('set', $captcha_key, null);

        $auth_token = Common::authcode($member['mid'], 'ENCODE', $user, 3600);
        $token = md5($auth_token);
        // 保存到服务器
        Model_Api_V2_Common::cache('set', $token, $auth_token);

        return array('verify_token' => $token);
    }

    public function reset_password(array $params): array
    {

        /**
         * @var $user
         * @var $pwd
         * @var $verify_token
         */
        extract($params);

        $auth_token = Model_Api_V2_Common::cache('get', $verify_token);
        if (empty($auth_token)) {
            throw new Exception(__("验证失败，已过期"));
        }

        $mid = Common::authcode($auth_token, 'DECODE', $user);
        if (empty($mid)) {
            throw new Exception(__("验证失败"));
        }

        $member = Model_Member::member_find($user);
        if (empty($member) || $member['mid'] != $mid) {
            throw new Exception(__("error_user_noexists"));
        }

        $user_type = strpos($user, '@') !== false ? 'email' : 'mobile';
        $pwd = Model_Member::make_pwd($pwd);
        DB::update('member')
            ->set(array('pwd' => $pwd))
            ->where($user_type, '=', $user)
            ->execute();

        Model_Api_V2_Common::cache('set', $verify_token, null);

        return array();
    }
}